<template>
  <el-container class="h-100p">

    <el-header height="45px" class="dv-header lh-45 bor-b">
      <div class="pull-right">
        <span @click="back(true)"><i class="icon-save"></i> 保存</span>
        <span class="mar-l-10" @click="back(false)"><i class="icon-back"></i> 退出</span>
      </div>
    </el-header>

    <el-container>

      <el-aside :width="aside.left.show ? '300px' : '40px'" class="elc-aside-left">
        <div class="dataview-aside-header" :class="{'dataview-aside-header-min': !aside.left.show}">
          <span class="dataview-aside-header-title">数据配置</span>
          <span class="cur-p" :class="{'pull-right': aside.left.show}"><i @click="toggleAside('left')" :class="{'el-icon-s-fold': aside.left.show , 'el-icon-s-unfold': !aside.left.show}"></i></span>
        </div>
        <div :class="{'hidden': aside.left.show == false}" class="pad-lr-20 pad-tb-15">
          <div class="datav-props-group">
            加载数据 <el-switch size="medium" class="mar-l-10" v-model="widget.meta.loadData"></el-switch>
          </div>

          <div v-if="widget.meta.loadData">
            <div class="datav-props-group">
              <span>数据源</span>
              <el-select size="medium" @change="datasourceChange" v-model="widget.meta.query.dataSource.id" placeholder="请选择数据源">
                <el-option
                  v-for="item in dataSources"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.type }}</span>
                </el-option>
              </el-select>
            </div>

            <div class="datav-props-group">
              <span>查询表达式</span>
              <el-input
                size="medium"
                type="textarea"
                :rows="4"
                placeholder="请输入查询表达式"
                v-model="widget.meta.query.expression">
              </el-input>
            </div>

            <div class="datav-props-group text-right">
              <el-button :loading="btnLoading" size="small" type="primary" @click="loadRedashData">执行</el-button>
            </div>
          </div>
        </div>
      </el-aside>



      <el-main>
        <div class="data-view-design-main-widget">
          <el-card class="h-100p">
            <rs-widget v-if="showWidget" :widget="widget"></rs-widget>
          </el-card>
        </div>
        <div class="data-view-design-main-footer">
          <div class="dataview-aside-header">
            <span class="dataview-aside-header-title">规格配置</span>
          </div>
          <div v-if="loadDataed || !widget.meta.loadData" class="pad-10">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-collapse v-model="collapseActiveName" accordion>
                  <el-collapse-item v-for="(item , index) in widgetTypes" :title="item.name" :key="index + ''" :name="item.name + index">
                    <div 
                      class="data-view-widget-type"
                      @click="widgetChange(itemWidgetType)"
                      :class="{
                        'data-view-widget-type-active': widget.meta.widgeTypeId === itemWidgetType.id , 
                        'hidden': widget.meta.loadData === false && itemWidgetType.loadData !== false
                      }" 
                      :key="itemWidgetType.id"
                      v-for="itemWidgetType in item.children">
                      <i :class="itemWidgetType.icon"></i>
                      <p :title="itemWidgetType.name">{{itemWidgetType.name}}</p>
                    </div>
                  </el-collapse-item>
                </el-collapse>

              </el-col>
              <el-col :span="12">
                <el-collapse>
                  <el-collapse-item v-for="(item , index) in widget.meta.dataset" :title="item.name || ('规格配置' + (index > 0 ? '-' + (index + 1) : ''))"  :key="index + ''" :name="index+ ''">
                    <div class="mar-b-10" v-for="(spec , index1) in item.specs" :key="index1 + ''">
                      <span class="dis-ib w-60">{{spec.name}}</span>
                      <el-select v-if="spec.type === 'field'" @change="widgetCheck" size="medium" v-model="spec.value" placeholder="请选择">
                        <el-option
                          v-for="field in fields"
                          :key="field.friendly_name"
                          :label="field.friendly_name"
                          :value="field.name">
                        </el-option>
                      </el-select>
                      <el-input  v-if="spec.type === 'input'" v-model="spec.value" placeholder="请输入内容"></el-input>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-main>


      <el-aside :width="aside.right.show ? '300px' : '40px'" class="elc-aside-right">
        <div class="dataview-aside-header" :class="{'dataview-aside-header-min': !aside.right.show}">
          <span class="dataview-aside-header-title">属性配置</span>
          <span class="cur-p" :class="{'pull-right': aside.right.show}"><i @click="toggleAside('right')" :class="{'el-icon-s-fold': !aside.right.show , 'el-icon-s-unfold': aside.right.show}"></i></span>
        </div>
        <div :class="{'hidden': aside.right.show == false}" class="pad-lr-20 pad-tb-15">
        
          <el-collapse v-if="widgetType">
            <el-collapse-item v-for="(item , index) in widgetType.options" :title="item.name"  :key="index" :name="index+ ''">
              <template v-for="(opt , index1) in item.children">
                <div v-if="getShow(opt)" :key="index1" class="mar-b-10">
                  <span class="dis-ib w-80">{{opt.name}}</span>
                  <el-select class="w-80-c" v-if="opt.type === 'field'" @change="widgetPropChange" size="medium" v-model="opt.value" placeholder="请选择">
                    <el-option
                      v-for="field in fields"
                      :key="field.friendly_name"
                      :label="field.friendly_name"
                      :value="field.name">
                    </el-option>
                  </el-select>
                  <el-select class="w-80-c" v-if="opt.type === 'select'" @change="widgetPropChange" size="medium" v-model="opt.value" placeholder="请选择">
                    <el-option
                      v-for="listItem in opt.selectList"
                      :key="listItem.name"
                      :label="listItem.name"
                      :value="listItem.value">
                    </el-option>
                  </el-select>
                  <el-input-number class="w-80-c"  v-if="opt.type === 'number'" @change="widgetPropChange" size="medium" v-model="opt.value" label="请输入"></el-input-number>
                  <el-input class="w-80-c"  v-if="opt.type === 'text'" @change="widgetPropChange" size="medium" v-model="opt.value" placeholder="请输入内容"></el-input>
                  <el-switch v-if="opt.type === 'boolean'" @change="widgetPropChange" size="medium" v-model="opt.value"></el-switch>
                </div>
              </template>
            </el-collapse-item>
          </el-collapse>
        </div>

      </el-aside>


    </el-container>
  </el-container>
</template>
<script>
import { WidgetModel } from '../models/widget.model';
import utils from '../utils';
import RsWidget from '../widget';

import { redashService } from '@/api/datav';

export default {
  components: {
    'rs-widget': RsWidget
  },
  data(){
    return {
      widget: new WidgetModel(),
      btnLoading: false,
      loadDataed: false,
      aside: {
        left: {
          show: true
        },
        right: {
          show: true
        }
      },
      collapseActiveName: '',
      widgetType: null,
      fields: [],
      showWidget: false
    }
  },
  props: {
    _widget: {
      type: Object,
      default: null
    },
    _dataSources: {
      type: Array,
      default: () => {
        return [];
      }
    },
    _widgetTypes: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  mounted(){
    this.init();
  },
  computed: {
    dataSources: function(){
      return this._dataSources;
    },
    widgetTypes: function(){
      return this._widgetTypes;
    }
  },
  methods: {
    init(){
      if(this._widget === null){
        // this.widget = new WidgetModel();
        this.widget.meta.id = utils.createId();
      }else{
        this.widget = this._widget;
        this.widgetType = utils.findWidgetType(this.widgetTypes , this.widget.meta.widgeTypeId);
      }
      console.log(this.widget , this.widgetTypes);
    },
    datasourceChange(currId){
      this.dataSources.forEach(
        item => {
          if(item['id'] === currId){
            this.widget.meta.query.dataSource.name = item['name'];
            this.widget.meta.query.dataSource.type = item['type'];
          }
        }
      );
      this.widgetCheck();
    },
    loadRedashData(){
      if(!this.widget.meta.query.dataSource.id || !this.widget.meta.query.expression){
        this.$message({
          type: 'error',
          message: '数据源和表达式不能为空'
        })
      }else{
        this.btnLoading = true;
        this.fields = [];
        redashService.loadRedashData(this.widget.meta.query , {}).then(
          res => {
            if(res['columns']){
              this.fields = res['columns'];
            }
            this.loadDataed = true;
            this.btnLoading = false;
          }
        );
      }
    },
    toggleAside(type){
      this.aside[type].show = !this.aside[type].show;
    },
    widgetChange(widgetType){

      this.widget.meta.widgeTypeId = widgetType.id;
      this.widget.meta.widgetType = widgetType.type;
      this.widget.meta.selector = widgetType.selector;
      this.widget.meta.dataset = [];
      (widgetType.dataset || []).forEach(
        item => {
          let newItem = {
            name: item.name,
            specs: []
          }
          item.specs.forEach(
            spec => {
              newItem.specs.push({
                type: spec.type,
                name: spec.name,
                code: spec.code,
                value: ''
              })
            }
          )
          this.widget.meta.dataset.push(newItem);
        }
      )
      this.widgetType = utils.findWidgetType(this.widgetTypes , this.widget.meta.widgeTypeId);
      this.setWidgetTypeOptionValue(this.widgetType.options || [] , this.widget.meta.privates);
      this.widget.meta.privates = {};
      this.createOption(this.widgetType.options || [] , this.widget.meta.privates);
      this.widgetCheck();
    },
    widgetPropChange(){
      this.widget.meta.privates = {};
      this.createOption(this.widgetType.options || [] , this.widget.meta.privates , 'value');
    },
    setWidgetTypeOptionValue(options , parentOption){
      options.forEach(
        (item , index) => {
          let currentCode = item.code.split('.').pop();
          if(item.children){
            this.setWidgetTypeOptionValue(item.children , parentOption[currentCode]);
          }else{
            item['value'] = parentOption && parentOption[currentCode] !== undefined ? parentOption[currentCode] : item['default'];
          }
        }
      )
    },
    createOption(options , parentOption){
      options.forEach(
        item => {
          let currentCode = item.code.split('.').pop();
          let prevOption = parentOption;
          if(item.children){
            prevOption[currentCode] = {};
            this.createOption(item.children , prevOption[currentCode]);
          }else{
            prevOption[currentCode] = item['value'] !== undefined ?  item['value'] : item['default'];
          }
        }
      )
    },
    widgetCheck(){
      let showWidget = true;
      if(!this.widget){
        showWidget = false;
        return;
      }
      this.widget.meta.dataset.forEach(
        item => {
          item.specs.forEach(
            spec => {
              if(!spec.value){
                showWidget = false;
              }
            }
          )
        }
      )
      if(!this.widget.meta.widgetType || !this.widget.meta.widgeTypeId || !this.widget.meta.selector ){
        showWidget = false;
      }
      this.showWidget = showWidget;
    },
    getValueByCode(codes , parent){
      let codeArr = codes.split('.');
      let code = codeArr.shift();
      if(parent){
        if(codeArr.length){
          return this.getValueByCode(codeArr.join('.') , parent[code]);
        }else{
          return parent[code];
        }
      }else{
        return null;
      }
    },
    getShow(opt){
      if(opt.show === false){
        return false;
      }else{
        let show = true;
        if(opt.displayCondition){
          opt.displayCondition.forEach(
            item => {
              let value = this.getValueByCode(item.code , this.widget.meta.privates);
              if(value !== item.value){
                show = false;
              }
            }
          )
        }
        return show;
      }
    },
    back(save){
      if(save){
        this.$emit('save' , this.widget);
      }else{
        this.$emit('cancel' , null);
      }
    }
  }
}
</script>
<style lang="scss" scoped>
 @import './design-widget.scss';
</style>